Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

702
Views
React/Jest - How to simulate touch "swipe" event

I have a component that triggers a function call whenever a swipe interaction was done. This swipe interaction can either be executed by touchEvent or mouseEvent. My goal was to check if the function was called, whenever a swipe occured. But I fail to simulate the touchEvent in a jest test. Using swiper, react, react-testing-library and jest.

Online Editor link for testing: Codesandbox

The actual class

const App = ({ funcCalledOnSlideChange }) => {
  return (
    <Swiper
      pagination={{
        clickable: true
      }}
      modules={[Pagination]}
      watchOverflow
      onSlideChange={funcCalledOnSlideChange}
    >
      <SwiperSlide>
        <img className="slide" />
      </SwiperSlide>
      <SwiperSlide>
        <img className="slide-second" />
      </SwiperSlide>
    </Swiper>
  );
};

And the actual test

const mockFunc = jest.fn();

function sendTouchEvent({ x, y, element, eventType }) {
  const touchObj = new Touch({
    identifier: Date.now(),
    target: element,
    clientX: x,
    clientY: y,
    radiusX: 2.5,
    radiusY: 2.5,
    rotationAngle: 10,
    force: 0.5
  });

  const touchEvent = new TouchEvent(eventType, {
    cancelable: true,
    bubbles: true,
    touches: [touchObj],
    targetTouches: [],
    changedTouches: [touchObj]
  });

  element.dispatchEvent(touchEvent);
}

test("should swipe by touch event", async () => {
  const { container } = render(<App funcCalledOnSlideChange={mockFunc} />);
  const swiperSlide = container.querySelector(".swiper-slide");

  act(() => {
    sendTouchEvent({
      x: 350,
      y: 100,
      element: swiperSlide,
      eventType: "touchstart"
    });
    sendTouchEvent({
      x: 200,
      y: 100,
      element: swiperSlide,
      eventType: "touchmove"
    });
    sendTouchEvent({
      x: 150,
      y: 100,
      element: swiperSlide,
      eventType: "touchend"
    });
  });

  await waitFor(() => {
    expect(mockFunc).toBeCalled();
  });
});

Actual error:

Failed to construct 'Touch': Failed to read the 'target' property from 'TouchInit': Failed to read the 'target' property from 'TouchInit': Required member is undefined.
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!